import { baseName } from '@/const'
import { getDynamicMenus } from '@/router/helper/utils'
import type { RouteItem } from '@/router/interface'
import type { AuthStore } from '@/store/interface/auth'

export default defineStore(`${baseName}__authStore`, (): AuthStore => {
  const authMenuList = ref<RouteItem[]>([])

  const menuList = computed(() => authMenuList.value)
  const fltMenus = computed(() => _filterAuthMenuList(authMenuList.value))

  async function getAuthMenuList(): Promise<RouteItem[]> {
    const menus = await getDynamicMenus()
    authMenuList.value = menus

    return menus
  }

  function clearAuthMenuList() {
    authMenuList.value = []
  }

  function _filterAuthMenuList(menuList: RouteItem[]): RouteItem[] {
    return menuList.filter((item) => {
      if (item.meta && item.meta.hidden) {
        return false
      }
      if (item.children) {
        item.children = _filterAuthMenuList(item.children)
      }
      return true
    })
  }

  return {
    authMenuList,
    fltMenus,
    menuList,
    getAuthMenuList,
    clearAuthMenuList,
  }
})
